package ajaxjs.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * TEST
 * 			out.write(new Net().get("http://gznet.com")); 
			out.write(new Net().post("http://gznet.com", null, null)); 
			out.write(new Net().getClientIP(request)); 
			out.write(new Net().getClient_Data(request, false)); 
 * @author Sp42

 */
public class Net {
	
	/**
	 * FAST Version
	 * @param url
	 * @param cookie
	 * @return
	 * @throws IOException
	 */
	public static String request(String url, HashMap<String, String> cookie) throws IOException{
	    String result = "", line;
		// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
		// String getURL = GET_URL + "&activatecode=" + URLEncoder.encode(url);
	    URL getUrl = new URL(url);
	    HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
	    
	    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
	    connection.setRequestProperty("Host", getUrl.getHost());

	    if(cookie != null){ // 设置请求的 Cookie 写死了
	    	String cookieStr = "";
		    for (String key : cookie.keySet())cookieStr += key + "=" + cookie.get(key) + ";";
			
			cookieStr = cookieStr.substring(0, cookieStr.length()-1);
	    	connection.setRequestProperty("Cookie", cookieStr);
		}

	    connection.connect();

	    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

	    while ((line = reader.readLine()) != null){
	    	result += line;
	    	// lines = new String(line.getBytes(), "utf-8");
	        // System.out.println(line);
	    }

	    reader.close();
	    connection.disconnect();// 断开连接

	    return result;		
	}
 	public static String request(String url) throws IOException{
 		return request(url, null);
 	}
 	
	private final String uaString = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2";
	private final String FORM_POST_ContentType = "application/x-www-form-urlencoded;charset=utf-8";
	
	public HttpURLConnection connectionObj;
	
	/**
	 * 同步请求远端数据，可带上 cookie
	 * @param url
	 * @param cookie
	 * @return
	 */
	public String get(String url, Map<String, String> cookie){
		 
		// 拼凑get请求的URL字串，使用URLEncoder.encode对特殊和不可见字符进行编码
		// url = URLEncoder.encode(url);
		
		String result = "";
		System.out.println("请求 URL::: " + url);
		URL getUrl = null;
		try{
			getUrl = new URL(url);
		}catch(java.net.MalformedURLException e){
			e.printStackTrace();
		}catch(Exception e){
			System.out.println(url + "不合法 ");
			e.printStackTrace();
			return null;
		}
		
		HttpURLConnection connection = this.getConnection(getUrl, cookie);
		
		try {
			connection.connect();
			result = readStream(connection);
		}catch(java.net.SocketTimeoutException e){
			System.out.println(":::请求超时！:::" + url);
		}catch (java.io.IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if(connection != null)connection.disconnect();// 断开连接
		 
		return result;
	}
	
	public String get(String url){
		return get(url, null);
	}
	
	public String post(String url, String requestData, Map<String, String> cookie) throws IOException{
		String result = "";
		// System.out.println("url:" + url); 
		// System.out.println("requestData:" + requestData); 

		URL getUrl = null;
		try{
			getUrl = new URL(url);
		}catch(java.net.MalformedURLException e){
			
		}
		
		HttpURLConnection connection = this.getConnection(getUrl, cookie);
		
		connection.setDoOutput(true); // for conn.getOutputStream().write(someBytes);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-type", FORM_POST_ContentType);
		
		connection.connect();

	 	if(requestData != null){
		 	java.io.OutputStream os = connection.getOutputStream();  
		    os.write(requestData.getBytes()); 
			os.flush();
			os.close();
	 	}
		
		result = readStream(connection);

		if(connection != null)connection.disconnect();// 断开连接

		return result;
	}
	
	public String post(String url, String requestData) throws java.io.IOException{
		return post(url, requestData, null);
	}
	
	/**
	 * 在请求中塞入 cookie
	 * @param cookie
	 * @param connection
	 */
	private void setCookie(java.util.Map<String, String> cookie, HttpURLConnection connection){
	    if(cookie != null){ 
	    	String cookieStr = "";
		    for (String key : cookie.keySet())
		    	cookieStr += key + "=" + cookie.get(key) + ";";
			
			cookieStr = cookieStr.substring(0, cookieStr.length() - 1); // 删掉最后一个分号
	    	connection.setRequestProperty("Cookie", cookieStr);
		}
	}
	
	/**
	 * 建立连接
	 * @param getUrl
	 * @param cookie
	 * @return
	 */
	private HttpURLConnection getConnection(URL getUrl, java.util.Map<String, String> cookie){
		HttpURLConnection connection = null;
		
		try{
			connection = (HttpURLConnection)getUrl.openConnection();
		}catch(java.io.IOException e){
			return null;
		}
		
		connection.setConnectTimeout(8000);  
		connection.setReadTimeout(8000);  
		connection.setUseCaches(false);  
		connection.setRequestProperty("User-Agent", uaString);
		connection.setRequestProperty("Host", getUrl.getHost());
			
		this.connectionObj = connection;
			
		setCookie(cookie, connection);
		
		return connection;
	}
	
	/**
	 * 读取流
	 * @param connection
	 * @return
	 * @throws java.io.IOException 
	 */
	private String readStream(HttpURLConnection connection) throws IOException{
		return ajaxjs.Util.readStream(connection.getInputStream());
	}

//	private String readStream(HttpURLConnection connection) throws IOException{
//		java.io.BufferedReader reader = null;
//		
//		StringBuffer result = new StringBuffer();
//		String line = null;
//		
//		try{
//			reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream(), "utf-8"));
//			
//			while ((line = reader.readLine()) != null){
//				result.append(line);
//				// lines = new String(line.getBytes(), "utf-8");
//			}
//		}catch(java.io.UnsupportedEncodingException e){
//			return null;
//		}finally{
//			if(reader != null)reader.close();
//		}
//		
//		return result.toString();
//	}
}
